import router from '@/router'

export default {
  namespaced: true,
  state:{
    collapsed:false,
    menuList:sessionStorage.getItem('menu')?JSON.parse(sessionStorage.getItem('menu')):[],
    MenuTags:[
      {
        title:'主页',
        path:'/home',
        canClose:false,
        active:true
      }
    ],
    currentPath:'/home'
  },
  mutations:{
    // 菜单展开/收缩
    toggleCollapsed:function (state) {
      state.collapsed = !state.collapsed
    },
    // 获取所有菜单
    getMenuList(state,payload){
      state.menuList = payload
    },
    // 点击左侧菜单弹出新标签
    addMenuTags(state,payload){
      state.MenuTags.forEach(function (item,index) {
        if(item.path === payload.path){
          item.active = true
        }else{
          item.active = false
        }
      })
      const canAdd = state.MenuTags.some(function (item) {
        if(item.path === payload.path){
          return true
        }
        return false
      })
      // console.log(state.MenuTags)
      // console.log(canAdd)
      !canAdd && state.MenuTags.push(payload)
    },
    // 关闭标签
    closeMenuTags(state,payload){
      // console.log(payload)
      state.MenuTags.forEach(function (item,index) {
        if(item.path === payload.path){
          item.active = true
        }else{
          item.active = false
        }
      })
      state.MenuTags.some(function (item,index) {
        if(item.path === payload.path && item.canClose){
          // console.log(index,item)
          state.MenuTags.splice(index,1)
          state.MenuTags[state.MenuTags.length-1].active = true
          if(location.pathname === state.MenuTags[state.MenuTags.length-1].path){
            return true
          }
          router.push(state.MenuTags[state.MenuTags.length-1].path)
          return true
        }
        return false
      })
      // console.log(state.MenuTags[state.MenuTags.length-1].path)
    },
    // 切换标签和路由
    switchMenuTags(state,payload){
      state.MenuTags.forEach(function (item,index) {
        if(item.path === payload.path){
          item.active = true
        }else{
          item.active = false
        }
      })
      router.push(payload.path)
    },
  }
}